<?php
/*
 * page to display an individual timesheet for a user
*/
//check for an admin session
include("../inc_files/utils/checksession.php");
//include the page header
include("../inc_files/ui/header.php");
// Create connection
include("../inc_files/utils/dbconnection.php");
//query for the timesheet, statuses and period details (which days are non working, is the period closed etc.)
$query ="SELECT timesheets.TimesheetID, timesheets.Deleted, timesheets.Comments,
		timesheet_statuses.StatusID, timesheet_statuses.Status, timesheet_periods.StartDate,
		timesheet_periods.MonStatus, timesheet_periods.TueStatus, timesheet_periods.WedStatus,
		timesheet_periods.ThurStatus, timesheet_periods.FriStatus, timesheet_periods.SatStatus,
		timesheet_periods.SunStatus, timesheet_periods.Closed, timesheet_periods.PeriodID, timesheets.Timesheet_User
		FROM	timesheets, timesheet_statuses, timesheet_periods
		WHERE TimesheetPeriod = ? AND Timesheet_User = ?
		AND timesheet_statuses.StatusID = timesheets.Status AND
		timesheet_periods.PeriodID = timesheets.TimesheetPeriod;;";
if($stmt = $mysqli -> prepare($query))	{
	//bind the customerid to the query
	$stmt -> bind_param("ss", $periodID, $userID);

	//sanitise the input data
	$periodID = $mysqli->real_escape_string(trim($_GET["id"]));

	$userID = $_SESSION["userid"];

	//execute the query
	$result = $stmt -> execute();

	//store the results
	$stmt->store_result();

	//bind the results to variables
	$stmt -> bind_result($timesheetID, $deleted,$comments, $statusID, $tsStatus,
			$startDate, $monStatus, $tueStatus, $wedStatus,
			$thurStatus, $friStatus, $satStatus, $sunStatus,
			$periodClosed, $periodID, $userID);

	//actually fetch the results
	$stmt->fetch();

	//close the statement
	$stmt -> close();

}
?>
<title>My Timesheet</title>
<!--include the script to hide/reveal the new item row-->
<script
	type="text/javascript" src="../scripts/async.js"></script>
<!--include the script to hide/reveal the new item row-->
<script type='text/javascript'>
//show/hide the new item row
	function togglenewitem() {
		if (document.getElementById('newitemrow').className == 'datagrid hidenewitem') {
			document.getElementById('newitemrow').className = 'datagrid shownewitem';
		} else {
			document.getElementById('newitemrow').className = 'datagrid hidenewitem';
		}
	}

	//refresh of timesheet lines datagrid
	function refreshgrid(){
		//cache the current form values so they can be reset after the form is re-written incase user modified values
		var cachedValues = new Array();	
		var s = "";
		var el = document.getElementById('timsheetlinesform').elements;
		for(var i = 0; i < el.length; i++){
			if(el[i].id.indexOf('#') != -1){
				cachedValues[el[i].id] = el[i].value;
			}
		}
		var nochache = Math.floor(Math.random() * 10000);
		//refresh data synchronously so we can access the form fields to calculate the totals row
		getasync('a_timesheetlines.php?timesheetid=<?php echo $timesheetID?>&nocache='+nochache,'datagrid', false);	
		//reset form values using previously cached values
		for (var key in cachedValues){
			if(document.getElementById(key)){	
				document.getElementById(key).value  = cachedValues[key];					
				s+=key+"="+cachedValues[key]+"\n";			
			}	
		}	
		//update the totals row...
		calculateColumnTotals();
			
	}

	//deletion of timesheet line
	function deleteline(lineID){		
		//confirm deletion with user
		if(confirm("Are you sure you want to delete this line?"))
		{		
			//delete task then refresh the data grid with new data		
			postasync('a_deleteline.php','value','lineid='+lineID, false); 
			refreshgrid();			
		}		
	}

	//save timesheet
	function savetimesheet(){
	var el = document.getElementById('timsheetlinesform').elements;
	var formdata = "";
    for(var i = 0; i < el.length; i++)
    {
    	if(el[i].id.indexOf('#') != -1){
            
    		formdata += el[i].id + "~" + el[i].value + "|";
			
        }

    }

    //remove the last trailing |
    formdata = 'formdata=' + formdata.slice(0,-1);
    //submit the changes
   	postasync('a_updatetimesheet.php', 'value', formdata, false);    
	alert("Timesheet saved");
	
	}
	//on change of the projects drop down list create a tasks drop down
	//displaying available tasks for the selected project
	function processddl(timesheetID){
		var ddl = document.getElementById('projectddl');
		if(ddl.selectedIndex == 0){
			document.getElementById('ddltasks').innerHTML = "";
		}  else {
			var projectid = ddl.options[ddl.selectedIndex].value;		
			//fill the drop down list for tasks for the selected project
			var nochache = Math.floor(Math.random() * 10000);
			getasync('a_createtasksddl.php?projectid='+projectid+'&nocache='+nochache+'&timesheetid='+timesheetID,'ddltasks', true);
		}
		//make sure the green tick is hidden until a taks is selected
		document.getElementById('tasksubmitimage').style.visibility="hidden";	

	}

	//if a project and a task have been selected then show the green tick button to allow this timesheet line to be added
	function allowsubmit(){
		var ddl = document.getElementById('tasksddl');
		if(ddl.selectedIndex == 0){
			document.getElementById('tasksubmitimage').style.visibility="hidden" ;
		}  else {
			document.getElementById('tasksubmitimage').style.visibility="visible" ;	
		}

	}
	//on clicking the green tick button add new timesheet line
	function addtimesheetline(){
		var ddl = document.getElementById('tasksddl');
		var taskid = ddl.options[ddl.selectedIndex].value;
		if(ddl.selectedIndex != 0){
			// create a new timesheet line then refresh the data grid with new data
			document.getElementById('ddltasks').innerHTML = postasync('a_addtimesheetline.php','element','taskid='+taskid+'&timesheetid='+<?php echo $timesheetID?>,  false); 
			refreshgrid();
		}
	}

	//on cell change, calculate totals row for each column
	function calculateColumnTotals(){		
		var sunTotal  = 0, monTotal  = 0, tueTotal  = 0, wedTotal  = 0, thurTotal  = 0, friTotal  = 0, satTotal  = 0;
		var el = document.getElementById('timsheetlinesform').elements;
			for(var i = 0; i < el.length; i++){
				if(el[i].id.substr(0,4)=='Sun#') sunTotal+= parseFloat(el[i].value);
				if(el[i].id.substr(0,4)=='Mon#') monTotal+= parseFloat(el[i].value);
				if(el[i].id.substr(0,4)=='Tue#') tueTotal+= parseFloat(el[i].value);
				if(el[i].id.substr(0,4)=='Wed#') wedTotal+= parseFloat(el[i].value);
				if(el[i].id.substr(0,5)=='Thur#') thurTotal+= parseFloat(el[i].value);
				if(el[i].id.substr(0,4)=='Fri#') friTotal+= parseFloat(el[i].value);
				if(el[i].id.substr(0,4)=='Sat#') satTotal+= parseFloat(el[i].value);
				
			}
			//update the totals row
			document.getElementById('TotalSun').value = sunTotal;
			if (sunTotal > 24) {
				document.getElementById('TotalSun').className = "tstotalover24"
			} else if (sunTotal > 8) {
				document.getElementById('TotalSun').className = "tstotalover8"
			} else {
				document.getElementById('TotalSun').className = "tstotalnormal"
			}
			document.getElementById('TotalMon').value = monTotal;
			if (monTotal > 24) {
				document.getElementById('TotalMon').className = "tstotalover24"
			} else if (monTotal > 8) {
				document.getElementById('TotalMon').className = "tstotalover8"
			} else {
				document.getElementById('TotalMon').className = "tstotalnormal"
			}
			document.getElementById('TotalTue').value = tueTotal;
			if (tueTotal > 24) {
				document.getElementById('TotalTue').className = "tstotalover24"
			} else if (tueTotal > 8) {
				document.getElementById('TotalTue').className = "tstotalover8"
			} else {
				document.getElementById('TotalTue').className = "tstotalnormal"
			}
			document.getElementById('TotalWed').value = wedTotal;
			if (wedTotal > 24) {
				document.getElementById('TotalWed').className = "tstotalover24"
			} else if (wedTotal > 8) {
				document.getElementById('TotalWed').className = "tstotalover8"
			} else {
				document.getElementById('TotalWed').className = "tstotalnormal"
			}
			document.getElementById('TotalThur').value = thurTotal;
			if (thurTotal > 24) {
				document.getElementById('TotalThur').className = "tstotalover24"
			} else if (thurTotal > 8) {
				document.getElementById('TotalThur').className = "tstotalover8"
			} else {
				document.getElementById('TotalThur').className = "tstotalnormal"
			}
			document.getElementById('TotalFri').value = friTotal;
			if (friTotal > 24) {
				document.getElementById('TotalFri').className = "tstotalover24"
			} else if (friTotal > 8) {
				document.getElementById('TotalFri').className = "tstotalover8"
			} else {
				document.getElementById('TotalFri').className = "tstotalnormal"
			}
			document.getElementById('TotalSat').value = satTotal;
			if (satTotal > 24) {
				document.getElementById('TotalSat').className = "tstotalover24"
			} else if (satTotal > 8) {
				document.getElementById('TotalSat').className = "tstotalover8"
			} else {
				document.getElementById('TotalSat').className = "tstotalnormal"
			}			
		}
//validate field changes to make sure that they are numbers, no more than 1 decimal place and less than 24 hours
	function validateHoursFields(field){
		number = field.value;
		var reg = /^([0-1][0-9]|[2][0-3]|[0-9])(\.[0-9])?$/;
		//returns true
		if(!number.match(reg) ){
			//if the field value is not a valid number set the field value back to what it was
			field.value = window.temporaryFieldValue;	
			}else{
				//if the field value is valid recalculate the totals
				calculateColumnTotals()
			}
		}

	
	
	</script>
</head>
<body>
	<?php 	include("../inc_files/ui/menu.php");?>

	<table style="width: 100%" class="inputform">
		<tr>
			<td class="tsheaderlabelcell">Tmesheet</td>
			<td class="tsheaderformcell"><?php echo $periodID;?></td>
		</tr>
		<tr>
			<td class="tsheaderlabelcell">Week start</td>
			<td class="tsheaderformcell"><?php echo date_format(new DateTime($startDate), 'd/m/Y')?>
			</td>

		</tr>
		<tr>
			<td class="tsheaderlabelcell">User</td>
			<td class="tsheaderformcell"><?php echo $userID;?></td>
		</tr>
		<tr>
			<td class="tsheaderlabelcell">Status</td>
			<td class="tsheaderformcell"><?php echo $tsStatus; if($periodClosed == 1) echo " - Timesheet Period Closed";?>
			</td>
		</tr>
		<tr>
			<td class="separatorrow" colspan="2"></td>

		</tr>
		<tr>
			<td colspan="2">
				<form id="timsheetlinesform" action="#">
					<div id="datagrid"></div>
				</form>
			</td>
		</tr>
	</table>


	<?php 	include("../inc_files/ui/footer.php");?>
	<script type="text/javascript">	
//populate the datagrid on page load
refreshgrid();
//create a variable at the window scope to temporarily store a field's value.  If a field fails
//validation i.e. it's not a number less than 24 and it is not in one of the the following
//formats 00.0, 0.0, 0 or 00 then the temorarily stored value is used to replace the invalid value
window.temporaryFieldValue = 0;

	</script>
</body>
</html>
